<template>
  <div class="container home-icon-list">
    <div class="button-block">
      <el-button v-if="rightsButtons['add']" type="success" icon="el-icon-plus" size="small" @click="showAdd">添加栏目</el-button>
      <el-button v-if="rightsButtons['sort']" type="primary" size="small" @click="handleSort">{{sortState==='view' ?'设置排序':'保存'}}</el-button>
    </div>
    <el-card style="margin-top:15px">
      <el-tabs v-model="currentTab" type="card" @tab-click="tabClick">
        <el-tab-pane label="显示" name="visibleTab"></el-tab-pane>
        <el-tab-pane label="隐藏" name="hideTab"></el-tab-pane>
      </el-tabs>
      <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
        <el-table-column align="center" label="标题" prop="name" min-width="100"></el-table-column>
        <el-table-column align="center" label="原图" prop="icon" width="100">
          <template slot-scope="scope">
            <img :src="scope.row.icon" width="30" height="30" alt="">
          </template>
        </el-table-column>
        <el-table-column align="center" label="限时图片" prop="limitedIcon" width="100">
          <template slot-scope="scope" v-if="scope.row.limitedIcon">
            <img :src="scope.row.limitedIcon" width="30" height="30" alt="">
          </template>
        </el-table-column>
        <el-table-column align="center" label="限时时间" prop="beginTime" min-width="160">
          <template slot-scope="scope" v-if="scope.row.beginTime">
            <div>{{scope.row.beginTime}}</div>
            <div>~</div>
            <div>{{scope.row.endTime}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型" prop="type" width="150">
          <template slot-scope="scope" v-if="scope.row.type">
            <div v-if="typeArray.filter(i => i.value===scope.row.type).length">
              {{(typeArray.filter(i => i.value===scope.row.type))[0].name}}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="排序" prop="sort" width="150">
          <template slot-scope="scope">
            <span v-show="sortState === 'view'">{{scope.row.sort}}</span>
            <el-input v-show="sortState === 'edit'" v-model="scope.row.sort" maxlength="5" style="width:80px"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="显示/隐藏" prop="sort" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isShow"
              :active-value="0"
              :inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleVisible(scope.row)"
              :disabled="!rightsButtons['visible']">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createdAt" width="100"></el-table-column>
        <el-table-column align="center" label="更新时间" prop="updatedAt" width="100"></el-table-column>
        <el-table-column align="center" label="操作" prop="sort" min-width="100" v-if="rightsButtons['edit']">
          <template slot-scope="scope">
            <el-button size="mini" @click="showEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal">
      </el-pagination>
    </el-card>
    <el-dialog :title="formData.id ? '编辑' : '新建'" :visible.sync="dialogVisible" width="50%">
      <el-form :model="formData" ref="form" label-width="150px">
        <el-form-item label="标题：" prop="name" :rules="commonRules.notNullRule">
          <el-input v-model="formData.name" maxlength="4"></el-input>
        </el-form-item>
        <el-form-item label="标题颜色：" prop="color">
          <el-input v-model="formData.color" placeholder="例如：#f6f6f6"></el-input>
        </el-form-item>
        <el-form-item label="图片：" prop="icon" :rules="commonRules.notNullRule">
          <el-upload
            class="avatar-uploader"
            :action="upladUrl"
            accept="image/*"
            name="file"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="(res) => { formData.icon = res.filePath }">
            <img v-if="formData.icon !==''" class="avatar" :src="formData.icon">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span style="color:red;position:absolute;right:20px;top:50px">*建议图片尺寸：70 * 70</span>
        </el-form-item>
        <el-form-item label="启用限时图片：" prop="limitedTime">
          <el-radio-group v-model="formData.limitedTime" size="medium">
            <el-radio border :label="0">关闭</el-radio>
            <el-radio border :label="1">限时时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formData.limitedTime === 1">
          <el-form-item label="限时时间：">
            <el-date-picker
              v-model="tempLimitTime"
              type="datetimerange"
              placeholder="选择日期时间"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="限时图片：" prop="limitedIcon" :rules="commonRules.notNullRule">
            <el-upload
              class="avatar-uploader"
              :action="upladUrl"
              accept="image/*"
              name="file"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="(res) => { formData.limitedIcon = res.filePath }">
              <img v-if="formData.limitedIcon !==''" class="avatar" :src="formData.limitedIcon">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <span style="color:red;position:absolute;right:20px;top:50px">*建议图片尺寸：70 * 70</span>
          </el-form-item>
        </template>
        <el-form-item label="跳转类型：" prop="type">
          <el-select v-model="formData.type" placeholder="请选择" @change="formData.typeValue=''">
            <el-option v-for="(item, index) in typeArray" :key="index" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item v-if="formData.type === '30'||formData.type === '31'" label="跳转等级：" prop="typeValue" label-width="150px">
          <el-radio v-model="formData.memberCardType" label="-1">不限制</el-radio>
          <el-radio v-model="formData.memberCardType" label="0">普通</el-radio>
          <el-radio v-model="formData.memberCardType" label="1">VIP</el-radio>
          <el-radio v-model="formData.memberCardType" label="2">钻石</el-radio>
          <el-radio v-model="formData.memberCardType" label="3">董事</el-radio>
        </el-form-item> -->
        <el-form-item v-if="formData.type === '13'" label="跳转淘宝官方活动：" prop="typeValue" label-width="150px">
          <span>{{formData.typeTitle||formData.typeValue}}</span>
          <el-button type="primary" plain @click="chooseJump">请选择</el-button>
        </el-form-item>
        <el-form-item label="跳转方式:" v-if="formData.type === '13'&&formData.typeValue">
        <el-radio v-model="formData.gotoWay" :label="0">直接跳转淘宝</el-radio>
        <el-radio v-model="formData.gotoWay" :label="1" :disabled="radioDisabled">跳转活动中间页</el-radio>
      </el-form-item>
        <el-form-item v-if="formData.type === '0' || formData.type === '14'" label="跳转地址：" prop="typeValue">
          <el-input v-model="formData.typeValue" placeholder="请输入URL"></el-input>
        </el-form-item>
        <el-form-item v-else-if="formData.type === '3'" label="标签名称：" prop="typeValue">
          <el-select v-model="formData.typeValue" placeholder="请选择">
            <el-option v-for="(item,index) in tagArray" :key="index" :label="item.name" :value="item.id+''"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else-if="formData.type === '50'||formData.type === '51'" label="小程序path：" prop="typeValue">
          <el-input v-model="formData.typeValue" placeholder="不填，默认小程序首页"></el-input>
        </el-form-item>
        <el-form-item label="安卓显示:" prop="androidShowInfo.status">
          <el-radio v-model="formData.androidShowInfo.status" :label="1">全版本显示</el-radio>
          <el-radio v-model="formData.androidShowInfo.status" :label="2">全版本不显示</el-radio>
          <el-radio v-model="formData.androidShowInfo.status" :label="3">仅指定版本号显示</el-radio>
          <el-radio v-model="formData.androidShowInfo.status" :label="4">仅指定版本号不显示</el-radio>
        </el-form-item>
        <el-form-item v-if="formData.androidShowInfo.status > 2" label="安卓版本号:" prop="androidShowInfo.versionList" :rules="commonRules.notNullRule">
          <div class="version-add">
            <el-row>
              <el-col :span="5"><el-input type="number" v-model="androidVersion.first"></el-input></el-col>
              <el-col :span="1" align="center">.</el-col>
              <el-col :span="5"><el-input type="number" v-model="androidVersion.second"></el-input></el-col>
              <el-col :span="1" align="center">.</el-col>
              <el-col :span="5"><el-input type="number" v-model="androidVersion.third"></el-input></el-col>
              <el-col :span="7" align="center">
                <el-button type="primary" size="mini" @click="addVersion('android')">添加版本</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="version-list">
            <el-tag v-for="(item, index) in formData.androidShowInfo.versionList" :key="index" effect="dark" closable @close="handleVersion('androidShowInfo', index)">{{item}}</el-tag>
          </div>
        </el-form-item>
        <el-form-item label="iOS显示:" prop="iosShowInfo.status">
          <el-radio v-model="formData.iosShowInfo.status" :label="1">全版本显示</el-radio>
          <el-radio v-model="formData.iosShowInfo.status" :label="2">全版本不显示</el-radio>
          <el-radio v-model="formData.iosShowInfo.status" :label="3">仅指定版本号显示</el-radio>
          <el-radio v-model="formData.iosShowInfo.status" :label="4">仅指定版本号不显示</el-radio>
        </el-form-item>
        <el-form-item v-if="formData.iosShowInfo.status > 2" label="iOS版本号:" prop="iosShowInfo.versionList" :rules="commonRules.notNullRule">
          <div class="version-add">
            <el-row>
              <el-col :span="5"><el-input type="number" v-model="iosVersion.first"></el-input></el-col>
              <el-col :span="1" align="center">.</el-col>
              <el-col :span="5"><el-input type="number" v-model="iosVersion.second"></el-input></el-col>
              <el-col :span="1" align="center">.</el-col>
              <el-col :span="5"><el-input type="number" v-model="iosVersion.third"></el-input></el-col>
              <el-col :span="7" align="center">
                <el-button type="primary" size="mini" @click="addVersion('ios')">添加版本</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="version-list">
            <el-tag v-for="(item, index) in formData.iosShowInfo.versionList" :key="index" effect="dark" closable @close="handleVersion('iosShowInfo', index)">{{item}}</el-tag>
          </div>
        </el-form-item>
        <el-form-item label="h5显示:" prop="h5ShowInfo">
          <el-radio v-model="formData.h5ShowInfo" :label="1">显示</el-radio>
          <el-radio v-model="formData.h5ShowInfo" :label="2">不显示</el-radio>
        </el-form-item>
        <el-form-item label="小程序显示:" prop="miniAppShowInfo">
          <el-radio v-model="formData.miniAppShowInfo" :label="1">显示</el-radio>
          <el-radio v-model="formData.miniAppShowInfo" :label="2">不显示</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save" :loading="btnLoading">保存</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { tbActivityGet } from '@/api/bihuasuan/taobaoActivity'
export default {
  name: 'iconList',
  data() {
    return {
      typeArray: [
        { name: 'h5', value: '0' },
        { name: '标签', value: '3' },
        { name: '碧家精选', value: '4' },
        { name: '碧选优品', value: '6' },
        { name: '商品分类', value: '7' },
        { name: '箱起', value: '9' },
        { name: '拼团', value: '10' },
        { name: '碧划算', value: '12' },
        // { name: '碧选小程序', value: '50' },
        { name: '碧选直播小程序', value: '51' },
        { name: '淘宝官方活动', value: '13' },
        { name: '团油', value: '14'},
        { name: '今日热卖', value: '15'},
        { name: '抽奖', value: '16'},
        { name: '会员免费领', value: '30'},
        { name: '会员低价购', value: '31'},
      ],
      tagArray: [], // 标签列表
      currentTab: 'visibleTab',
      sortState: 'view', // view: 非编辑状态、edit: 编辑状态
      listQuery: {
        pageIndex: 1,
        pageSize: 10
      },
      list: [],
      listTotal: 0,
      listLoading: false,

      androidVersion: {
        first: '',
        second: '',
        third: ''
      },
      iosVersion: {
        first: '',
        second: '',
        third: ''
      },

      formData: {
        id: '',
        name: '',
        color: '',
        icon: '',
        limitedIcon: '',
        limitedTime: 0,
        beginTime: '',
        endTime: '',
        type: '0',
        typeValue: '',
        typeTitle:'',
        gotoWay: 1,
        androidShowInfo: {
          status: 1,
          versionList: []
        },
        iosShowInfo: {
          status: 1,
          versionList: []
        },
        h5ShowInfo: 1,
        miniAppShowInfo: 1
      },
      tempLimitTime: [],
      dialogVisible: false,
      btnLoading: false,
      radioDisabled:false
    }
  },
  created() {
    this.fetchData()
    this.fetchTagData()
  },
  methods: {
     chooseJump(){
       if(this.formData.type === '13') {
        let checkData = [{
          id: this.formData.typeValue,
          activityName: this.formData.typeTitle,
          centerPage: this.formData.gotoWay===1?1:0,
        }];
        this.bhstaobaoActivity(checkData, 1).then(val => {
          this.formData.typeValue = val[0].id
          this.formData.typeTitle = val[0].activityName
          this.formData.gotoWay = val[0].centerPage
          if(val[0].centerPage===0) {
            this.radioDisabled = true
          } else {
            this.radioDisabled = false
          }
        })
        return false
      }
     },
    // 获取列表
    fetchData() {
      this.listLoading = true
      this.request({
        url: '/bsnl-product/ico/query',
        method: 'post',
        data: {
          ...this.listQuery,
          isShow: this.currentTab === 'visibleTab' ? 0 : 1
        }
      }).then(res => {
        this.list = res.data || []
        this.listTotal = res.totalCount
        this.listLoading = false
      }).catch(e => {
        this.listLoading = false
      })
    },
    // 获取tag列表
    fetchTagData() {
      this.listLoading = true
      this.request({
        url: '/bsnl-product/tag/query',
        method: 'post',
        data: {
          pageIndex: 1,
          pageSize: 100
        }
      }).then(res => {
        this.tagArray = res.data || []
      }).catch(e => {
        console.log(e)
      })
    },
    //切换每页条数
    handleSizeChange (value) {
      this.listQuery.pageSize = value;
      this.fetchData()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageIndex = page;
      this.fetchData()
    },
    // 添加栏目
    showAdd() {
      this.tempLimitTime = []
      this.formData = {
        id: '',
        name: '',
        color: '',
        icon: '',
        limitedIcon: '',
        limitedTime: 0,
        beginTime: '',
        endTime: '',
        type: '0',
        typeValue: '',
        typeTitle:'',
        gotoWay:1,
        androidShowInfo: {
          status: 1,
          versionList: []
        },
        iosShowInfo: {
          status: 1,
          versionList: []
        },
        h5ShowInfo: 1,
        miniAppShowInfo: 1
      }
      this.dialogVisible = true
    },
    // 编辑栏目
    showEdit(row) {
      this.request({
        url: '/bsnl-product/ico/details?id=' + row.id,
        method: 'get'
      }).then(res => {
        this.formData = {
          ...(res.data || {})
        }
        if (this.formData.limitedTime === 1){
          this.tempLimitTime = [this.formData.beginTime||'', this.formData.endTime||'']
        } else {
          this.tempLimitTime = []
        }
        this.dialogVisible = true
        if(res.data.type === '13') {
          tbActivityGet({id:res.data.typeValue}).then((res) =>{
            if(res.data.centerPage ===0) {
              this.radioDisabled = true
            } else {
              this.radioDisabled = false
            }
          })
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 设置排序
    handleSort() {
      if(this.sortState === 'view'){
        this.sortState = 'edit'
      } else {
        this.updateSort()
        this.sortState = 'view'
      }
    },
    // 更新排序
    updateSort() {
      let data = this.list.map(i => {
        return {
          id: i.id,
          sort: i.sort
        }
      })
      this.request({
        url: '/bsnl-product/ico/updateBatchSort',
        method: 'post',
        data,
      }).then(res => {
        this.$message.success('操作成功')
        this.fetchData()
        this.sortState = 'view'
      }).catch(e => {
        console.log(e)
      })
    },
    // 点击tab
    tabClick() {
      this.listQuery.pageIndex = 1
      this.fetchData()
    },
    // 点击显示/隐藏
    handleVisible(row) {
      this.request({
        url: '/bsnl-product/ico/updateShowStatus',
        method: 'post',
        data: {
          id: row.id,
          isShow: row.isShow
        }
      }).then(res => {
        this.$message.success('操作成功')
        this.fetchData()
      }).catch(e => {
        console.log(e)
      })
    },
    // 添加版本
    addVersion(type) {
      const keyVersion = this[`${type}Version`]
      if(keyVersion.first!=='' && keyVersion.second!=='' && keyVersion.third!==''){
        let version = `${keyVersion.first}.${keyVersion.second}.${keyVersion.third}`
        if (this.formData[`${type}ShowInfo`].versionList.includes(version)){
          this.$message.warning('该版本已存在')
        } else {
          this.formData[`${type}ShowInfo`].versionList.push(version)
        }
      } else {
        this.$message.warning('请输入完整的版本号')
      }
    },
    // 删除版本号
    handleVersion(type, index) {
      this.formData[type].versionList.splice(index, 1)
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }

        // this.btnLoading = true
        if (this.formData.limitedTime === 1) {
          this.formData.beginTime = this.tempLimitTime[0]
          this.formData.endTime = this.tempLimitTime[1]
        }
        if (['4', '6', '7', '8', '9', '10', '12'].includes(this.formData.type)) {
          this.formData.typeValue = this.formData.type
        }
        console.log(this.formData)
        this.request({
          url: this.formData.id ? '/bsnl-product/ico/updateAppHomeFunc' : '/bsnl-product/ico/saveAppHomeFunc',
          method: 'post',
          data: this.formData
        }).then(res => {
          this.dialogVisible = false
          this.btnLoading = false
          this.$message.success('操作成功')
          this.fetchData()
        }).catch(e => {
          this.btnLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss">
.home-icon-list{
  padding: 10px;
  .avatar-uploader .el-upload,
  .upload-img-list li,
  .upload-img-list .upload-btn {
    width: 100px;
    height: 100px;
    line-height: 98px;
  }
  .version-list{
    margin-top: 10px;
    min-height: 100px;
    padding: 0 10px;
    background: #f2f2f2;
  }
  .el-tag{
    margin-right: 12px;
  }
  .el-radio {
    margin-right: 12px;
  }
}
</style>
